package com.xdf.whiteaccount.controller;

import com.xdf.whiteaccount.entity.ResponseResult;
import com.xdf.whiteaccount.enums.ResponseEnum;
import com.xdf.whiteaccount.qrcodeutil.WechatQrCodeUtils;
import com.xdf.whiteaccount.service.LoginService;
import com.xdf.whiteaccount.vo.QrMsg;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: xzy-management-system
 * @description: 登录
 * @author: 张柯
 * @create: 2021-01-03 08:38
 **/
@Controller
@RequestMapping("/system")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Value("${defaultQrCodeTimeout}")
    private Long defaultQrCodeTimeout = 120L;
    @Autowired
    private WechatQrCodeUtils utils;

    /**
     * 获取二维码信息
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/qrcode")
    @ResponseBody
    public ResponseResult<QrMsg> getQrcode() throws Exception {
        UUID token = UUID.randomUUID();
        return ResponseResult.<QrMsg>builder()
                .success(true)
                .message(ResponseEnum.OK.getName())
                .data(QrMsg.builder()
                        .qrCodeUrl(utils.getQrCode(token.toString()))
                        .timeout(defaultQrCodeTimeout)
                        .token(token.toString()).build())
                .build();
    }

    /**
     * 登录用户
     *
     * @param qrcode
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseResult<Void> login(String qrcode) throws Exception {
        if (loginService.login(qrcode) <= 0) {
            return ResponseResult.<Void>builder().success(false).message("登录失败！无此用户！").build();
        }
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    /**
     * 登出账号
     *
     * @return
     */
    @PostMapping("/logout")
    @ResponseBody
    public ResponseResult<Void> logOut(HttpServletResponse response) throws IOException {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            SecurityUtils.getSubject().logout();
        }
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }
}